import React from 'react'
import Code from './Code'
import TreeList from '../ui-components/treeList'
import style from './style'
import { bindActionCreators } from 'redux'
import util from '../util'
import cx from 'classnames'

import { connect } from 'react-redux'
import { fetchTeams } from '../actions/team.action'

const ROOT_TEAM = '2b1e6d025ac28868'

export default 
@connect(({team}) => ({team}), dispatch => ({actions: bindActionCreators({ fetchTeams }, dispatch)}))
class extends React.Component {

  componentDidMount() {
    this.props.actions.fetchTeams()
  }

  makeTeamTree() {
    const { teams } = this.props.team
    if (util.isNull(teams)) return []

    function find(list) {
      if (!list.length) return []
      return list.map(item => {
        return {
          ...item,
          teams: find.call(this, teams.filter(team => util.isEqual(team.parentTeamId, item.teamId)))
        }
      })
    }

    return find.call(this, [{ teamId: ROOT_TEAM, teamName: 'root team' }])
  }

  handleClick(item) {
    console.log(item)
  }

  render() {
    const rootTeam = this.makeTeamTree()[0]
    return (
      <div className={cx({
        [style.root]: true
      })}>
        <Code>{'<TreeList/>'}</Code>
        <div>
          <TreeList
            onClick={::this.handleClick}
            root={rootTeam}
          />
        </div>
      </div>
    )
  }
}
